var form, table, select, menuIdSelect;
var roleId = getTempData('updateRoleId');

$(function () {
    initLayUI(function () {
        initData();
        initButtons();
    });
});

function initLayUI(cb) {
    layui.use(['form', 'table', 'xmSelect'], function () {
        form = layui.form;
        table = layui.table;
        select = layui.xmSelect;

        form.render();

        form.on('submit(roleEditForm)', function (data) {
            let menuIds = menuIdSelect.getValue('value');
            if (menuIds.length === 0) {
                layerUtil.error("请至少选择一个菜单权限");
                return false;
            }
            let role = {
                "roleName": data.field.roleName,
                "roleKey": data.field.roleKey,
                "menuIds": menuIds,
            };
            if (roleId !== undefined) {
                role.roleId = roleId;
                updateRole(role);
            } else {
                addRole(role);
            }
            return false;
        });

        cb();
    });
}

function initButtons() {
    $("#cancelBtn").click(function () {
        layerUtil.closeLayer(parent.window.iframeIndex);
    });
}

function initData() {
    initMenuData(function () {
        initRoleData();
    });
}

function initMenuData(cb) {
    ajaxUtil.simpleGet("/menu/queryMenuTree", function (data) {
        menuIdSelect = select.render({
            el: '#menuIds',
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            tree: {
                show: true,
                showFolderIcon: true,
                strict: false
            },
            data: data
        });

        cb();
    });
}

function initRoleData() {
    if (roleId !== undefined) {
        ajaxUtil.simpleGet("/role/queryRoleById?roleId=" + roleId, function (data) {
            form.val('form', {
                "roleName": data.roleName,
                "roleKey": data.roleKey,
            });
            // 多选选中
            menuIdSelect.setValue(data.menuIds);
        });
    }
}

function addRole(role) {
    ajaxUtil.simplePost(role, "/role/add", function () {
        layerUtil.closeLayer();
        reloadParentTable('roleTable');
    });
}

function updateRole(role) {
    ajaxUtil.simplePost(role, "/role/update", function () {
        layerUtil.closeLayer();
        reloadParentTable('roleTable');
    });
}